<template>
  <div class="business">
    <el-container>
      <el-header>
        <div class="top">
          <h3>出差申请</h3>
          <div class="icons">
            <el-icon size="22" class="icang"><SuccessFilled /></el-icon>
            <el-icon size="22"><Operation /></el-icon>
            <el-icon size="22"><More /></el-icon>
          </div>
        </div>
        <div class="nav">
                         <!-- 新增数据思路: 显示表单, 填写表单数据, 提交表单(表单验证), 验证通过时发请求到服务端, 保存数据到服务端, 返回新增的结果. -->
                <!-- 删除数据思路: 获取删除项的id, 发请求到服务器, 服务器执行删除并返回删除的结果. -->
                <!-- 编辑数据思路: 显示表单, 回显旧数据, 填写新的表单数据, 提交表单(表单验证), 验证通过时发请求到服务端, 保存数据到服务端, 返回编辑的结果. -->

                <!-- 新增和编辑共用一个表单: 如何区分提交操作是"新增"还是"编辑", 可以在提交时判断表单数据中是否有id -->
                

                <!-- 导出的思路一: 点击导出按钮, 向服务端发请求, 服务端返回数据到前端, 前端保存数据到excel文件/pdf文件等( 可以借助 file-saver 实现 ) -->
                <!-- 导出的思路二 : 点击导出按钮, 向服务端发请求, 服务端处理数据并生成文件,返回文件到前端 -->
                <!-- 操作按钮 -->
                
                <!-- 导入/上传的思路: 点击按钮, 弹出文件选择框, 选择文件并上传文件到服务器( 往往需要提前设置 上传地址,上传请求的请求头参数, 上传字段名, 上传时附带的额外参数 ). -->

          <div class="btns">
            <el-button type="warning" @click="showDialog">发起新的</el-button>
            <!-- action 指定上传地址 -->
            <!-- headers 指定上传请求的请求头参数 -->
            <!-- name 指定上传字段名 -->
            <!-- data 上传时附带的额外参数 -->
            <!-- show-file-list 是否显示上传文件列表 -->
            <!-- disabled 是否禁用上传组件 -->
            <!-- accept 接受上传的文件类型,多个文件类型用分号分割 -->
            <!-- on-change 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用-->
            <!-- on-success 文件上传成功时的钩子 -->
            <!-- on-error 文件上传失败时的钩子 -->
            <p>
              <el-upload
                action="/api/business/import"
                :headers="headers"
                name="excel"
                accept=".xlsx, .slx"
                :on-change="onChange"
                :on-success="onSuccess"
                :on-error="onError"
                :show-file-list="false"
                :data="{ userid: formData.userid }"
              >
                <el-button :loading="uploading">导入</el-button>
              </el-upload>
            </p>
          </div>
          <el-tabs v-model="activeName" class="tabs" @tab-change="handleClick">
            <el-tab-pane label="待办事项" name="1"></el-tab-pane>
            <el-tab-pane label="已办事项" name="2"></el-tab-pane>
            <el-tab-pane label="抄送事项" name="3"></el-tab-pane>
            <el-tab-pane label="我发起的" name="4"></el-tab-pane>
            <el-tab-pane label="全部数据" name="5"></el-tab-pane>
            <el-tab-pane label="概览" name="6"></el-tab-pane>
            <el-tab-pane label="统计报表" name="7"></el-tab-pane>
          </el-tabs>
        </div>
      </el-header>
      <el-main>
        <div class="content">
          <div class="cont_top">
            <ul>
              <li>
                <el-icon><MessageBox /></el-icon>
                <el-link
                  :href="'/api/business/download?userid=' + formData.userid"
                  target="_blank"
                  >导出</el-link
                >
              </li>
              <li>
                <el-icon><Setting /></el-icon>字段管理
              </li>
              <li>
                <el-icon><FullScreen /></el-icon>精简视图
              </li>
              <li>
                <el-icon><Search /></el-icon>搜索
              </li>
            </ul>
          </div>
          <!-- 表格 -->
          <el-table
            ref="multipleTableRef"
            :data="tableData"
            border
            min-width="700px"
            style="width: 100%"
          >
            <!-- prop 字段名称 对应列内容的字段名 -->
            <!-- show-overflow-tooltip 当内容过长被隐藏时显示 tooltip -->
            <!-- formatter 用来格式化内容 -->
            <el-table-column type="selection" width="55" />
            <el-table-column
              prop="_id"
              label="编号"
              width="120"
              show-overflow-tooltip
            />
            <el-table-column
              prop="status"
              label="当前流程"
              width="120"
              :formatter="formatterStatus"
            />
            <el-table-column prop="name" label="申请人" width="120" />
            <el-table-column prop="reason" label="出差事由" width="200" />
            <el-table-column
              prop="starttime"
              label="出发日期"
              width="200"
              :formatter="formatterTime"
            />
            <el-table-column
              prop="endtime"
              label="返回日期"
              width="200"
              :formatter="formatterTime"
            />
            <el-table-column prop="days" label="出差总天数" width="120" />
            <el-table-column label="操作" property="address">
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  size="small"
                  @click.prevent="editRow(scope)"
                >
                  编辑
                </el-button>
                <el-button
                  link
                  type="primary"
                  size="small"
                  @click.prevent="deleteRow(scope)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-pagination
          @size-change="sizeChange"
          :page-size="10"
          class="pagination"
          @current-change="handleCurrentChange"
          :default-page-size="5"
          background
          layout="prev, pager, next"
          :total="total"
        />
      </el-main>
    </el-container>
  </div>

  <!-- 抽屉 -->
  <el-drawer
    ref="drawerRef"
    v-model="addDialog"
    title="出差申请"
    direction="rtl"
    custom-class="demo-drawer"
  >
    <div class="demo-drawer__content">
      <!-- 新增表单 -->
      <el-form
        :model="formData"
        label-position="top"
        :rules="rules"
        ref="formRef"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="申请人" prop="name">
              <el-input v-model="formData.name" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在部门">
              <el-input v-model="formData.dept" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="出差事由说明" prop="reason">
              <el-input
                type="textarea"
                v-model="formData.reason"
                placeholder="输入内容"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出发日期" prop="starttime">
              <el-date-picker
                v-model="formData.starttime"
                type="date"
                placeholder="选择一个出发日期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="返回日期" prop="endtime">
              <el-date-picker
                v-model="formData.endtime"
                type="date"
                placeholder="选择一个返回日期"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="出差总天数" prop="days">
              <el-input v-model="formData.days" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div class="demo-drawer__footer">
        <el-button @click="addDialog = false">取消</el-button>
        <el-button type="primary" @click="onSubmit(formRef)"
          >提交申请</el-button
        >
      </div>
    </div>
  </el-drawer>
</template>

<script setup>
import { reactive, ref, onMounted } from "vue";
import {
  business_list,
  business_add,
  business_delete,
  business_edit,
} from "../../api/api";
const formLabelWidth = "100px";
var addDialog = ref(false);
var tableData = ref([]);
var formRef = ref();
var total = ref(0);

var uploading = ref(false);

var formData = ref({
  userid: JSON.parse(localStorage.getItem("userinfo"))._id,
  name: JSON.parse(localStorage.getItem("userinfo")).name,
  reason: "",
  starttime: "",
  endtime: "",
  days: "",
});

var headers = ref({
  Authorization: "Bearer" + " " + localStorage.getItem("token"),
});
//组件挂载完成时, 请求出差申请列表
onMounted(async () => {
  var userinfo = JSON.parse(localStorage.getItem("userinfo"));
  var res = await business_list({ userid: userinfo._id, page: 1 });
  console.log(res);
  tableData.value = res.data.list;
  total.value = res.data.total
});

//验证 申请人
const validateName = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入申请人"));
  } else {
    callback();
  }
};
//验证 出差事由
const validateReason = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入出差事由"));
  } else {
    callback();
  }
};
//验证 出发日期
const validateStarttime = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请选择一个出发日期"));
  } else {
    if (
      new Date(formData.value.starttime) - new Date(formData.value.endtime) >
      0
    ) {
      //返回日期必须大于出发日期
      formData.value.starttime = "";
      formData.value.days = "";
      callback(new Error("出发日期必须早于返回日期!"));
    } else if (formData.value.starttime && formData.value.endtime) {
      //出发日期,返回日期都存在, 计算总天数
      formData.value.days =
        (new Date(formData.value.endtime) -
          new Date(formData.value.starttime)) /
        (24 * 60 * 60 * 1000);
    }
    callback();
  }
};
//验证 返回日期
const validateEndtime = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请选择一个返回日期"));
  } else {
    if (
      new Date(formData.value.starttime) - new Date(formData.value.endtime) >
      0
    ) {
      //返回日期必须大于出发日期
      formData.value.endtime = "";
      formData.value.days = "";
      callback(new Error("返回日期必须大于出发日期!"));
    } else if (formData.value.starttime && formData.value.endtime) {
      //出发日期,返回日期都存在, 计算总天数
      formData.value.days =
        (new Date(formData.value.endtime) -
          new Date(formData.value.starttime)) /
        (24 * 60 * 60 * 1000);
    }
    callback();
  }
};

//验证 出差总天数
const validateDays = (rule, value, callback) => {
  if (value === "" || Number(value) == 0) {
    callback(new Error("请填写正确的总天数"));
  } else {
    callback();
  }
};

//表单的验证规则 rules
const rules = reactive({
  name: [{ validator: validateName, trigger: "blur", required: true }],
  reason: [{ validator: validateReason, trigger: "blur", required: true }],
  starttime: [
    { validator: validateStarttime, trigger: "blur", required: true },
  ],
  endtime: [{ validator: validateEndtime, trigger: "blur", required: true }],
  days: [{ validator: validateDays, trigger: "blur", required: true }],
});
//格式化 流程状态
var formatterStatus = function (row, column, cellValue, index) {
  return cellValue == 0 ? "审核中" : "已通过";
};

//分页
var handleCurrentChange = async (page) => {
  //请求page对应页码的数据
  var userinfo = JSON.parse(localStorage.getItem("userinfo"));
  var res = await business_list({ userid: userinfo._id, page });
  tableData.value = res.data.list;
};
// var sizeChange= async(page)=>{
//      arr.value = tableData.value.slice(page,2)
// }

//补零
var addZero = (num) => {
  return num < 10 ? "0" + num : num;
};

//格式化时间
var formatterTime = function (row, column, cellValue, index) {
  var d = new Date(cellValue);
  return `${d.getFullYear()}-${addZero(d.getMonth() + 1)}-${addZero(
    d.getDate()
  )}`;
};

// 点击申请按钮
var showDialog = () => {
  // 显示抽屉
  addDialog.value = true;
  // 方式一
  formData.value = {
    userid: JSON.parse(localStorage.getItem("userinfo"))._id,
    name: JSON.parse(localStorage.getItem("userinfo")).name,
    reason: "",
    starttime: "",
    endtime: "",
    days: "",
  };
  // // 方式二    有缺陷
  // formRef.value.resetFields(); //重置表单
  // delete formData.value._id;//删除_id属性
};

// 编辑
var editRow = (scope) => {
  // scope.row 点击的这一行数据    formData当前表单现有的数据
  console.log(scope.row, formData);
  // 显示抽屉
  addDialog.value = true;
  //回显 当前行的出差申请的数据
  //formData.value = scope.row;//直接用对象给对象赋值,容易导致数据之间互相影响( 最好在赋值之前做个深拷贝 )
  formData.value = JSON.parse(JSON.stringify(scope.row));
};
// 删除
var deleteRow = async (scope) => {
  //scope.$index
  //scope.row 当前行的数据对象
  //scope.row._id 当前行的数据对象的id
  var userinfo = JSON.parse(localStorage.getItem("userinfo"));
  var res = await business_delete({
    userid: userinfo._id,
    id: scope.row._id,
    page: 1,
  });
  if (res.data.code == 200) {
    ElNotification({
      //弹出通知
      title: "删除通知",
      message: res.data.msg,
      type: "success",
    });
  } else {
    ElNotification({
      title: "删除通知",
      message: res.data.msg,
      type: "error",
    });
  }
  tableData.value = res.data.list;
  total.value = res.data.total;
  console.log(tableData.value);
};

// var deleteRow = (scope) => {
//   var userinfo = JSON.parse(localStorage.getItem("userinfo"));
//   business_delete({
//     userid: userinfo._id,
//     id: scope.row._id,
//     page: 1,
//   }).then((res) => {
//     if (res.data.code == 200) {
//       ElNotification({
//         //弹出通知
//         title: "删除通知",
//         message: res.data.msg,
//         type: "success",
//       });
//     } else {
//         ElNotification({
//           title: "删除通知",
//           message: res.data.msg,
//           type: "error",
//         });
//       }
//   });
// };

// 提交表单
var onSubmit = (formRef) => {
  formRef.validate(async (valid) => {
    if (valid) {
      if (formData.value._id) {
        // 发起编辑请求
        // await business_edit( formData.value )
        ElNotification({
          //弹出通知
          title: "编辑通知",
          message: "编辑成功!",
          type: "success",
        });
        addDialog.value = false; //关闭抽屉
      } else {
        // 发请求，新增出差申请
        var res = await business_add(formData.value);
        if (res.data.code == 200) {
          ElNotification({
            //弹出通知
            title: "新增通知",
            message: res.data.msg,
            type: "success",
          });
          addDialog.value = false; //关闭抽屉
          // 添加的数据渲染到页面中
          tableData.value = res.data.list;
          total.value = res.data.total;
          formRef.resetFields(); //重置表单
        } else {
          ElNotification({
            title: "新增通知",
            message: res.data.msg,
            type: "error",
          });
        }
      }
    } else {
      console.log("error submit!");
      return false;
    }
  });
};



//添加文件、上传成功和上传失败时的回调
var onChange = ( uploadFile, uploadFiles) => {
   if( uploadFile.percentage < 100 ){
        uploading.value = true;//显示loading
    }
};

//文件上传成功时的回调
var onSuccess = (response, uploadFile, uploadFiles) => {
  uploading.value = false;//隐藏loading
  if (response.code == 200) {
    ElNotification({
      //弹出通知
      title: "导入通知",
      message: response.msg,
      type: "success",
    });
  }
};



//文件上传失败时的回调
var onError = (error, uploadFile, uploadFiles) => {
  if(error){
    ElNotification({ //弹出通知
          title: '导入通知',
          message: '导入失败!',
          type: 'error',
        })
  }
};
</script>

<style lang="scss" scoped>
header {
  height: 100px;
  & .top {
    padding: 20px;
    display: flex;
    align-items: center;
    padding-bottom: 20px;
    & .icons {
      display: flex;
      i {
        margin-left: 10px;
        font-size: 20px;
      }
      .icang {
        color: orange;
      }
    }
  }
  & .nav {
    width: 100vw;
    height: 50px;
    border-top: 1px solid rgb(200, 200, 200);
    border-bottom: 1px solid rgb(200, 200, 200);
    display: flex;
    align-items: center;
    & .btns {
      margin: 0 10px;
      display: flex;
      height: 50px;
      align-items: center;
      p {
        box-sizing: border-box;
        height: 42px;
        line-height: 39px;
      }
      button {
        margin-right: 10px;
      }
    }
    .tabs {
      height: 50px;
      line-height: 50px;
    }
  }
}

main {
  margin: 10px 0;
  .pagination {
    margin: 20px 0;
  }

  .content {
    .cont_top {
      ul {
        border: 1px solid rgb(222, 222, 222);
        list-style: none;
        display: flex;
        align-items: center;
        height: 40px;
        line-height: 40px;
        li {
          box-sizing: border-box;
          border-right: 1px solid rgb(211, 211, 211);
          padding: 0 15px;
          i {
            margin: 0 3px;
            vertical-align: middle;
          }
        }
        li:nth-child(4) {
          border-right: 1px solid transparent;
        }
      }
    }
  }
}
</style>